import React, { useState, useEffect } from 'react';
import { 
  IonPage, 
  IonContent, 
  IonHeader, 
  IonToolbar, 
  IonButtons, 
  IonMenuButton, 
  IonTitle,
  IonList,
  IonItem,
  IonLabel,
  IonAvatar,
  IonBadge,
  IonNote,
  IonButton,
  IonIcon,
  IonSearchbar,
  IonSegment,
  IonSegmentButton,
  IonRefresher,
  IonRefresherContent,
  IonInfiniteScroll,
  IonInfiniteScrollContent,
  useIonViewWillEnter
} from '@ionic/react';
import { 
  timeOutline, 
  checkmarkDone, 
  notificationsOutline, 
  mailUnreadOutline,
  chatbubbleEllipsesOutline,
  personCircleOutline,
  checkmarkCircle,
  trash,
  ellipsisHorizontal,
  arrowBack
} from 'ionicons/icons';
import { useHistory } from 'react-router-dom';

// 通知类型定义
type NotificationType = 'all' | 'unread' | 'system' | 'message' | 'mention';

interface Notification {
  id: string;
  title: string;
  content: string;
  timestamp: string;
  read: boolean;
  type: NotificationType;
  sender?: {
    name: string;
    avatar: string;
  };
}

const NotificationsPage: React.FC = () => {
  const history = useHistory();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [filteredNotifications, setFilteredNotifications] = useState<Notification[]>([]);
  const [selectedType, setSelectedType] = useState<NotificationType>('all');
  const [searchText, setSearchText] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  // 模拟加载通知数据
  const loadNotifications = (pageNum = 1, refresh = false) => {
    setIsLoading(true);
    
    // 模拟API请求延迟
    setTimeout(() => {
      const newNotifications: Notification[] = [];
      const startIndex = refresh ? 0 : (pageNum - 1) * 10;
      
      for (let i = startIndex; i < startIndex + 10; i++) {
        if (i >= 50) {
          setHasMore(false);
          break;
        }
        
        const types: NotificationType[] = ['system', 'message', 'mention'];
        const randomType = types[Math.floor(Math.random() * types.length)];
        
        newNotifications.push({
          id: `notif-${i}`,
          title: `通知标题 ${i + 1}`,
          content: `这是通知的内容摘要，描述了通知的详细信息。这是第 ${i + 1} 条通知内容。`,
          timestamp: `${Math.floor(Math.random() * 24)}小时前`,
          read: i % 4 === 0, // 每4条中有一条已读
          type: randomType,
          sender: {
            name: `用户${i}`,
            avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70) + 1}`
          }
        });
      }
      
      if (refresh) {
        setNotifications(newNotifications);
      } else {
        setNotifications([...notifications, ...newNotifications]);
      }
      
      setIsLoading(false);
    }, 800);
  };

  // 页面加载时获取通知
  useIonViewWillEnter(() => {
    loadNotifications();
  });

  // 筛选通知
  useEffect(() => {
    let filtered = notifications;
    
    // 按类型筛选
    if (selectedType !== 'all') {
      filtered = filtered.filter(notif => notif.type === selectedType);
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      filtered = filtered.filter(
        notif => 
          notif.title.toLowerCase().includes(searchLower) || 
          notif.content.toLowerCase().includes(searchLower)
      );
    }
    
    setFilteredNotifications(filtered);
  }, [notifications, selectedType, searchText]);

  // 处理下拉刷新
  const handleRefresh = (event: CustomEvent) => {
    setPage(1);
    setHasMore(true);
    loadNotifications(1, true);
    setTimeout(() => {
      event.detail.complete();
    }, 1000);
  };

  // 加载更多通知
  const loadMore = (event: CustomEvent) => {
    setPage(page + 1);
    loadNotifications(page + 1);
    setTimeout(() => {
      (event.target as HTMLIonInfiniteScrollElement).complete();
    }, 1000);
  };

  // 标记通知为已读
  const markAsRead = (id: string) => {
    setNotifications(notifications.map(notif => 
      notif.id === id ? { ...notif, read: true } : notif
    ));
  };

  // 标记所有通知为已读
  const markAllAsRead = () => {
    setNotifications(notifications.map(notif => ({ ...notif, read: true })));
  };

  // 删除通知
  const deleteNotification = (id: string) => {
    setNotifications(notifications.filter(notif => notif.id !== id));
  };

  // 清空所有通知
  const clearAllNotifications = () => {
    setNotifications([]);
  };

  // 获取通知图标
  const getNotificationIcon = (type: NotificationType) => {
    switch (type) {
      case 'system':
        return notificationsOutline;
      case 'message':
        return mailUnreadOutline;
      case 'mention':
        return chatbubbleEllipsesOutline;
      default:
        return notificationsOutline;
    }
  };

  // 获取通知类型文本
  const getNotificationTypeText = (type: NotificationType) => {
    switch (type) {
      case 'system':
        return '系统通知';
      case 'message':
        return '新消息';
      case 'mention':
        return '@提到';
      default:
        return '通知';
    }
  };

  // 查看通知详情
  const viewNotificationDetail = (id: string) => {
    markAsRead(id);
    history.push(`/notification/${id}`);
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          
          <IonTitle>通知</IonTitle>
          
          <IonButtons slot="end">
            <IonButton onClick={markAllAsRead}>
              <IonIcon slot="icon-only" icon={checkmarkDone} />
            </IonButton>
            <IonButton onClick={clearAllNotifications}>
              <IonIcon slot="icon-only" icon={trash} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
        
        {/* 搜索栏 */}
        <IonToolbar>
          <IonSearchbar 
            placeholder="搜索通知" 
            value={searchText}
            onIonChange={e => setSearchText(e.detail.value!)}
            animated
          />
        </IonToolbar>
        
        {/* 通知类型筛选 */}
        <IonToolbar>
          <IonSegment 
            value={selectedType} 
            onIonChange={e => setSelectedType(e.detail.value as NotificationType)}
            scrollable
          >
            <IonSegmentButton value="all">
              <IonLabel>全部</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="unread">
              <IonLabel>未读</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="system">
              <IonLabel>系统</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="message">
              <IonLabel>消息</IonLabel>
            </IonSegmentButton>
            <IonSegmentButton value="mention">
              <IonLabel>提到</IonLabel>
            </IonSegmentButton>
          </IonSegment>
        </IonToolbar>
      </IonHeader>
      
      <IonContent className="ion-padding">
        <IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
          <IonRefresherContent pullingIcon="lines"></IonRefresherContent>
        </IonRefresher>
        
        {/* 通知列表 */}
        {filteredNotifications.length > 0 ? (
          <IonList lines="full" className="notification-list">
            {filteredNotifications.map(notification => (
              <IonItem 
                key={notification.id} 
                button 
                detail={false}
                onClick={() => viewNotificationDetail(notification.id)}
                className={notification.read ? 'read' : 'unread'}
              >
                <div slot="start" className="notification-icon">
                  <IonIcon 
                    icon={getNotificationIcon(notification.type)} 
                    color={notification.read ? "medium" : "primary"} 
                  />
                </div>
                
                <IonLabel className="ion-text-wrap">
                  <h2>{notification.title}</h2>
                  <p>{notification.content}</p>
                  <div className="notification-meta">
                    <IonNote>
                      <IonIcon icon={timeOutline} size="small" />
                      {notification.timestamp}
                    </IonNote>
                    <IonNote>
                      {getNotificationTypeText(notification.type)}
                    </IonNote>
                  </div>
                </IonLabel>
                
                {!notification.read && (
                  <IonBadge slot="end" color="primary">新</IonBadge>
                )}
                
                {notification.sender && (
                  <IonAvatar slot="end">
                    <img src={notification.sender.avatar} alt={notification.sender.name} />
                  </IonAvatar>
                )}
              </IonItem>
            ))}
          </IonList>
        ) : (
          <div className="empty-state">
            <IonIcon icon={notificationsOutline} size="large" color="medium" />
            <h3>没有通知</h3>
            <p>您当前没有新的通知</p>
            <IonButton fill="outline" onClick={() => setSelectedType('all')}>
              查看所有通知
            </IonButton>
          </div>
        )}
        
        <IonInfiniteScroll 
          threshold="100px" 
          disabled={!hasMore}
          onIonInfinite={loadMore}
        >
          <IonInfiniteScrollContent
            loadingText="加载更多通知..."
            loadingSpinner="bubbles"
          />
        </IonInfiniteScroll>
      </IonContent>
    </IonPage>
  );
};

export default NotificationsPage;